<template>
  <div class="employees-container">
    <!-- 头部公共组件 -->
    <pageTools>
      <template #left> <el-tag>共5条记录</el-tag> </template>
      <template #right>
        <el-button
          v-arrowBtn="'q3'"
          size="mini"
          type="danger"
          @click="handleDownload"
        >excel导出</el-button>
        <el-button
          size="mini"
          type="success"
          @click="$router.push('/import?type=user')"
        >excel导入</el-button>
        <!-- <el-button size="mini" type="success" @click="$router.push({path:'/import',query:{type:'user'}})">==excel导入</el-button> -->
        <el-button
          size="mini"
          type="primary"
          @click="addEmp"
        >新增员工</el-button>
      </template>
      <template>
        <h1>我是匿名</h1>
      </template>
    </pageTools>

    <!-- 表格 -->
    <el-card>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />

        <el-table-column sortable prop="username" label="姓名" />
        <el-table-column label="头像" align="center">
          <template slot-scope="scoped">
            <img
              v-imgError="defaultImg"
              style="width: 40px; height: 40px"
              :src="scoped.row.staffPhoto"
              alt=""
            >
          </template>
        </el-table-column>
        <el-table-column sortable prop="mobile" label="手机号" />
        <el-table-column sortable prop="workNumber" label="工号" />
        <el-table-column sortable label="聘用形式">
          <template slot-scope="scoped">{{
            formatEmployment(scoped.row.formOfEmployment)
          }}</template>
        </el-table-column>
        <el-table-column sortable prop="departmentName" label="部门" />
        <el-table-column sortable prop="correctionTime" label="入职时间" />

        <el-table-column sortable label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleClick(scope.row)"
            >查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button
              type="text"
              size="small"
              @click="roleHandle(scope.row.id)"
            >角色</el-button>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 20px; text-align: right">
        <el-pagination
          :current-page="currentPage4"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageObj.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 对话框 -->
    <el-dialog title="添加员工" :visible.sync="dialogFormVisible">
      <empDia v-if="dialogFormVisible" @success="success" />
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
      <setRole
        v-if="dialogRoleVisible"
        ref="setRole"
        @success="dialogRoleVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import defaultImg from '@/assets/common/bigUserHeader.png'
import EmployeeEnum from '@/constant/employees'
import { getEmployeeList } from '@/api/employees'
 import empDia from './empDia.vue'
import setRole from './setRole.vue'
export default {
  name: '',
  components: {
    empDia,
    // empDia:()=> import('./empDia.vue'),
    setRole
  },
  data() {
    return {
      defaultImg,
      tableData: [],
      currentPage4: 4,
      pageObj: {
        page: 1,
        size: 5
      },
      total: 0,
      dialogFormVisible: false,
      tHeader: [],

      dialogRoleVisible: false
    }
  },
  computed: {},
  created() {
    this.loadEmp()
  },
  methods: {
    handleClick(row) {
      //  实现页面跳转 =====
      /*
      声明式导航   router-link
      编程式导航   this.$router.push()
      */
      // this.$router.push('/employees/detail/'+row.id)  === path: 'detail/:id',
      //  this.$router.push('/detail/' + row.id) //  path: '/detail/:id',
      // this.$router.push({ path: '/detail/' + row.id }) //  path: '/detail/:id',
      // this.$router.push({ name: 'detail', params: { id: row.id }})  /* name: 'detail', // 给路由规则加一个name   path: '/detail/:id', */
      // this.$router.push({
      //   name: 'detail',
      //   query: { id: row.id },
      //   params: { name: 'jack' }
      // }) /* name: 'detail', // 给路由规则加一个name     path: '/detail/:name', */
      // this.$router.push({
      //   name: 'detail',
      //   params: { id:row.id },
      //   query:{
      //     name:'jack',
      //     id:row.id
      //   }
      // })
      this.$router.push({
        name: 'detail',
        params: { id: row.id }
      })
    },
    async loadEmp() {
      const res = await getEmployeeList(this.pageObj)
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    /* 分页 */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageObj.size = val
      this.loadEmp()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageObj.page = val
      this.loadEmp()
    },
    formatEmployment(num) {
      // num = num || 1
      var obj = EmployeeEnum.hireType.find((item) => item.id == num)
      return obj ? obj.value : '未知'
    },
    addEmp() {
      this.dialogFormVisible = true
    },
    success() {
      // 添加员工成功后
      this.dialogFormVisible = false
      // 刷新页面
      this.loadEmp()
    },
    /* 导出 */
    async handleDownload() {
      // 获取所有的数据条数
      const res = await getEmployeeList({ page: 1, size: this.total })
      import('@/vendor/Export2Excel').then((excel) => {
        /* 定义表头 */
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const tHeader = this.tHeader
        /* 需要导出的数据 */
        const list = res.data.rows //  处理所有的数据
        const data = this.formatJson(list) // 返回值需要是一个二维数组
        console.log(data, 888)
        // const data = [
        //   ['1', 'web', 'java', 'python', 'php'],
        //   ['2', 'web2', 'java2', 'python2', 'php2']
        // ] // 返回值需要是一个二维数组
        console.log(data, list, 9988)
        excel.export_json_to_excel({
          // multiHeader: [
          //   ['姓名', '年龄', '性别', '爱好', '', '', '', '', '', ''],
          //   ['姓名22', '年龄22', '性别', '爱好', '', '', '', '', '', '222']
          // ], // 二位数组  设置多表头
          // merges: ['A1:A2','B1:D1'], // 相当于设置合并单元格
          header: this.tHeader, // 表头
          data, // 显示表格数据
          filename: 'web70', //  设置导出的文件名
          autoWidth: true, // 自动匹配表格宽度
          bookType: 'xlsx' //  设置文件导出的类型 文件后缀
        })
      })
    },
    formatJson(jsonData) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      this.tHeader = Object.values(map)
      console.log(this.tHeader, 66555)
      //  jsonData===>表格数据
      //  console.log(jsonData, 9988555)
      //  处理数据的====把英文转换成中文  还有时间需要转换===并且需要返回一个二维数组
      return jsonData.map((item) => {
        //  获取的每一项的数据有很多，我们需要做筛选
        var newObj = {} //  需要收集的字段数据
        var enKey = Object.keys(map) // 获取的是英文键[]
        enKey.forEach((key) => {
          //  会循环10次
          newObj[map[key]] = item[key]
        })
        console.log(newObj, 7777)
        return Object.values(newObj) // 获取的是收集对象中的值存在一个数组中
        //  ['1063705989926227968', 'c8b7722b1139bb9b346409e503302e82', '13800000002', '管理员', '2018-11-02T08:00:00.000+0000', 1, '2018-11-30T00:00:00.000+0000', '9002']
      })
    },

    /* 分配角色 */
    roleHandle(id) {
      /*
      步骤分析
      1-点击角色按钮
      2-显示对话框
      3-获取所有的角色
      4-获取当前点击用户所拥有的角色并选中
      5-点击确认按钮
        5-1 封装api
        5-2 调用
        5-3 发送请求
        5-4  成功后 关闭对话框
      */
      this.dialogRoleVisible = true
      this.$nextTick(() => {
        this.$refs.setRole.id = id
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.employees-container {
  padding: 30px;
}
</style>
